<template>
	<div>
    <Breadcrumb :style="{margin: '15px 0',float: 'left'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem>会员中心</BreadcrumbItem>
      <BreadcrumbItem>会员管理</BreadcrumbItem>
    </Breadcrumb>
    <Content class="layer-content">
      <Form inline>
        <FormItem>
          <Input style="width: 400px" v-model="keywords" search enter-button placeholder="请输入关键字" @on-search="searchGet" @submit.native.prevent/>
        </FormItem>
        <FormItem>
					<Select style="width: 150px" placeholder="用户角色" clearable @on-change="selectOption">
            <Option v-for="(item,index) in postRoleArray" :value="item.userRoleId" :key="index">{{item.roleName}}</Option>
          </Select>
				</FormItem>
        <FormItem>
					<Select style="width: 100px" placeholder="会员级别" clearable @on-change="doUserLevel">
            <Option :value="1">一级会员</Option>
            <Option :value="2">二级会员</Option>
            <Option :value="3">三级会员</Option>
            <Option :value="0">普通会员</Option>
          </Select>
				</FormItem>
        <FormItem>
					<Cascader style="width: 300px" placeholder="请选择地区" :data="regionArray" @on-change="regionSelector" :load-data="loadRegion"></Cascader>
				</FormItem>
        <FormItem>
          <Button @click="reset">重置</Button>
        </FormItem>
      </Form>
      <Table border :columns="columns" :data="dataGrid"></Table>
      <HigPager v-model="query" :total="pageTotal" :init="Init"></HigPager>
    </Content>
    <Modal :footer-hide="true" v-model="showRoleAuth" title="角色授权" width="70%" @on-cancel="onCancel">
      <Authorize ref="refAuthorize" :dataBus="dataVo" :callbank="callEvent" :key="keyIndex"></Authorize>
    </Modal>
  </div>  
</template>
<script scope>
import Authorize from './authorize.vue'
export default {
  data () {
    return {
      pageTotal: 0,
      keyIndex: 0,
      dataGrid:[],
      regionArray: [],
      postRoleArray: [],
      keywords: null,
      showRoleAuth: false,
      dataVo: {},
      query: {
        pageIndex: 1,
        pageSize: 15
      },
      columns: [
        {
          title: "用户姓名",
          key: "userName",
          width: 200
        },
        {
          title: "联系电话",
          key: "unionMobile",
          width: 180
        },
        {
          title: "会员等级",
          key: "userLevelEnum",
          width: 110
        },
        {
          title: "地区",
          key: "userRegion"
        },
        {
          title: "分销采购授权",
          key: "scmAuth",
          width: 130,
          render: (h, params) => {
            return h("div", [
              h('i-switch',{
                props: {
                  value: params.row.scmAuth,
                  disabled: params.row.userLevel === 0
                },
                scopedSlots: {
                  open: () => h('span', '开'),
                  close: () => h('span', '关')
                },
                on: {
                  'on-change': (value) => {
                    this.doAuthCode(params.row, value);
                  }
                }
              })
            ])
          }
        },
        {
          title: "注册时间",
          key: "postTime",
          width: 150,
          render: (h, params) => {
            return h("div", this.$date(params.row.postTime,'yyyy-MM-dd HH:mm'));
          },
        },
        {
          title: "操作",
          key: "action",
          width: 120,
          render: (h, params) => {
            return h("nav", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginLeft: "10px",
                  },
                  on: {
                    click: () => {
                      this.auth(params.row)
                    },
                  },
                },
                "角色授权"
              )
            ])
          },
        },
      ]
    }
  },
  components: {
    Authorize
  },
  methods: {
    //授权
    auth(e){
      this.dataVo = e
      this.$refs.refAuthorize.Init()
      this.showRoleAuth = true
    },
    onCancel() {
      this.keyIndex ++
    },
    callEvent(){
      this.showRoleAuth = false
      this.keyIndex ++
      this.Init()
    },
    //获取列表
    Init(){
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-uc',
        url: '/v1.0/view/union/user/plus/page',
        query: this.query,
        action: (res) => {
          if (res.data.code === 20000) {
            this.pageTotal = res.data.data.count
            this.dataGrid = res.data.data.list
            for(let item of this.dataGrid) {
              item.userName = item.userName ? item.userName : '匿名用户'
              item.userLevelEnum = this.userLevelEnum(item.userLevel)
              item.scmAuth = item.authCode ? item.authCode.includes('1922') : false
              if(item.countyName) {
                item.userRegion = item.provinceName + item.cityName + item.countyName
              }
            }
          } else {
            this.$Message.error(res.data.msg)
          }
        }
      }).get()
     },
     getPostRole() {
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-uc',
        url: '/v1.0/user/role/page',
        query: {
          pageIndex: 1,
          pageSize: 30
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.postRoleArray = res.data.data.list
          } else {
            this.$Message.error(res.data.msg)
          }
        }
      }).get()
    },
    regionInit() {
      new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: "0"
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.regionArray = data
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
    },
    loadRegion(item, callback) {
			item.loading = true
			new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: item.id,
            regionLevel: 4
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false
            callback()
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
		},
    regionSelector(value) {
      if(!this.query.equal) this.query.equal = new Object()
      this.query.equal.townshipCode = value[value.length - 1]
      this.Init()
		},
    selectOption(userRoleId) {
      if(!this.query.equal) this.query.equal = new Object()
      this.query.equal.userRoleId = userRoleId
      this.Init()
    },
    doUserLevel(level) {
      if(!this.query.equal) this.query.equal = new Object()
      this.query.equal.userLevel = level
      this.Init()
    },
     //搜索
    searchGet() {
      let sqlLike = {
        fields: ["user_name","user_mobile","id_card_no"],
        keyword: this.keywords,
      }
      this.query.sqlLike = sqlLike
      this.query.pageIndex = 1
      this.Init()
    },
    //重置
    reset() {
      delete this.query.sqlLike
      delete this.query.equal
      this.keywords = null
      this.Init()
    },
    userLevelEnum(level) {
      switch(level) {
        case 0:
          return '普通'
        case 1:
          return '一级'
        case 2:
          return '二级'
        case 3:
          return '三级'
        default:
          return '其它'
      }
    },
    doAuthCode(rows,bool) {
      console.log(rows,bool)
      let authCode = rows.authCode ? rows.authCode : '0'
      if(bool) {
        //打开
        authCode = authCode + ',1922'
      } else {
        authCode.replace(",1922", "")
      }
      new this.$rest({
        gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/user-src/update/union/user",
        data: {
          pojo: {
            userId: rows.userId,
            authCode: authCode
          }
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.$Message.success({
              content: bool?'开启成功':'关闭成功',
              duration: 1
            })
          } else {
            this.$Notice.warning({
              desc: `失败原因：${res.data.msg}`,
            });
          }
        },
      }).post()
    }
  },
  created(){
    this.Init()
    this.getPostRole()
    this.regionInit()
  }
}
</script>
<style lang="less" scoped>
.imgs {
  width: 80%;
}
</style>